package net.yxsoft.controller.common.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import rapid.core.ContextStateEnum;
import rapid.core.TResult;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @ClassName: GlobalExceptionHandler
 * @Description:全局异常处理器
 * @author: wj
 * @date: 2023/11/14 12:00
 */

public class GlobalExceptionInterceptor implements Interceptor {

    @Override
    public void intercept(Invocation inv) {
        try {
            inv.invoke();
        } catch (Exception e) {
            handleException(e, inv.getController());
        }
    }

    private void handleException(Exception e, Controller controller) {
        String errMsg;
        if (e instanceof NullPointerException) {
            errMsg = "发生空指针异常";
        } else if (e instanceof IllegalArgumentException) {
            errMsg = "发生非法参数异常";
        } else if (e instanceof ArrayIndexOutOfBoundsException) {
            errMsg = "发生数组越界异常";
        } else if (e instanceof FileNotFoundException) {
            errMsg = "发生文件未找到异常";
        } else if (e instanceof IOException) {
            errMsg = "发生IO异常";
        } else if (e instanceof SQLException) {
            errMsg = "发生SQL异常";
        } else if (e instanceof IllegalStateException) {
            errMsg = "发生状态异常";
        } else if (e instanceof ClassNotFoundException) {
            errMsg = "发生类未找到异常";
        } else if (e instanceof UnsupportedOperationException) {
            errMsg = "发生不支持的操作异常";
        } else {
            errMsg = "发生未知异常";
        }

        controller.setAttr("errMsg", errMsg);

        if (controller.getRequest().getRequestURI().endsWith(".html")) {
            // 如果是HTML页面，则渲染错误页面
            controller.renderError(500, errMsg);
        } else {
            // 否则，输出错误信息
            TResult result = new TResult();
            result.setState(ContextStateEnum.FAIL);
            result.setMessage(errMsg);
            controller.set("result", result);
            controller.render("/shared/error.html");
        }
    }
}